"""
这个模块定义了工具方法
"""
import re
import logging
import smtplib

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from flask import jsonify
from logging.handlers import RotatingFileHandler

from package.config import Config

PARAM_ERROR = {"msg": "Param Error"}

UNKNOWN_ERROR = {"msg": "Unkown Error"}

NOTFOUND_ERROR = {"msg": "404 Not Found"}

ALARM_SUBJECT = "农业大棚设备报警"

def ans_builder(*msg: any, status: bool = True, code: int = 200):
    """
    这个函数返回JSON序列化之后的消息以及状态码,可以直接作为响应返回

    Parameters:
        msg (any): The response text.
        status (bool): Execution result.
        code (int): Http status Code.

    Returns:
        tuple[Response, int]: Router Response.
    """
    ans = {"status": "success"} if status else {"status": "error"}
    for each in msg:
        ans.update(each)
    return jsonify(ans), code

def set_log_handler(logger: logging.Logger, config: Config) -> logging.Logger:
    """
    这个函数返回添加了自定义格式的LOG Handler后的标准Logger实例 

    Parameters:
        None.

    Returns:
        RotatingFileHandler: LOG Handler.
    """
    # TODO: Add Log formatter to the env
    # 创建日志记录器，指明日志保存路径,每个日志的大小，保存日志的上限
    handler = RotatingFileHandler(config.LogPath, encoding='UTF-8')
    # 设置日志的格式               发生时间         日志等级     日志信息文件名      行数        日志信息
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(lineno)s - %(message)s')
    # 将日志记录器指定日志的格式
    handler.setFormatter(formatter)
    # 日志等级的设置
    handler.setLevel(logging.INFO)
    logger.addHandler(handler)

    return logger

def mail(receiver_email: str, subject: str, body: str):
    """
    发送邮件辅助方法,向指定的邮箱发送邮件

    Parameters:
        None.

    Returns:
        Bool : OK or Not.
    """
    # 发件⼈邮箱
    sender_email = "cauc_iot_exercitation@outlook.com"
    # 发件⼈邮箱密码或授权码
    password = "@elysia@"

    # 创建邮件对象
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject
    # 将正⽂添加到邮件中
    message.attach(MIMEText(body, "plain"))

    try:
        smtp_server = 'smtp-mail.outlook.com'
        port = 587
        server = smtplib.SMTP(smtp_server, port)
        server.starttls() # 使⽤TLS加密连接
        server.login(sender_email, password) # 登录到邮箱
        server.sendmail(sender_email, receiver_email, message.as_string()) # 发送邮件
        # print("邮件已成功发送")
        return True

    except Exception as e:
        # print(f"发送邮件时出现错误：{str(e)}")
        return False
    finally:
        server.quit() # 关闭连接

def checkemail(email):
    """
    邮件格式校验函数，用于检测传入的邮件格式是否合法

    Parameters:
        email (str).

    Returns:
        Bool : OK or Not.
    """
    reg="\w+[@][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+"
    result=re.findall(reg,email)
    if result:
        return True   #邮箱合法
    else:
        return False    #邮箱不合法